Page({
  data: {
    candidate: {
      id: '',
      name: '',
      votes: 0,
      rank: 0,
      description: '',
      images: [],
      videoUrl: '',
      videoPoster: '',
      audioUrl: '',
      extraInfo: ''
    },
    activityId: '',
    loading: true,
    isDescExpanded: false, // 控制描述是否展开
    audioPlaying: false, // 音频播放状态
    audioContext: null as any, // 音频上下文
    audioDuration: 0, // 音频总时长
    audioCurrentTime: 0, // 音频当前播放时间
    audioProgress: 0, // 音频播放进度百分比
    audioCurrentTimeFormatted: '00:00', // 格式化的当前时间
    audioDurationFormatted: '00:00', // 格式化的总时长
    hasVotedForCandidate: false, // 用户是否已为此候选人投票
    voteStatus: {
      totalVoted: 0,
      voteLimit: 1,
      remainingVotes: 1,
      canVoteMore: true,
      votedCandidateIds: []
    }
  },

  onLoad(options: any) {
    // 获取选手ID和活动ID
    const candidateId = options.id
    const activityId = options.activityId
    
    console.log('选手ID:', candidateId, '活动ID:', activityId)
    
    if (!candidateId) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      })
      return
    }
    
    this.setData({
      activityId: activityId,
      'candidate.id': candidateId
    })
    
    // 获取选手详情
    this.getCandidateDetail(candidateId)
    
    // 检查投票状态
    this.checkVoteStatus()
  },

  onShow() {
    // 重新检查投票状态（从其他页面返回时）
    this.checkVoteStatus()
  },

  onHide() {
    // 页面隐藏时停止所有媒体播放
    console.log('页面隐藏，停止所有媒体播放')
    this.stopAllMedia()
  },

  onUnload() {
    // 页面卸载时停止所有媒体播放
    console.log('页面卸载，停止所有媒体播放')
    this.stopAllMedia()
  },

  // 页面触底
  onReachBottom() {
    // 防止在滚动时意外触发，这里不需要特殊处理
  },

  // 检查用户投票状态
  async checkVoteStatus() {
    const { activityId, candidate } = this.data
    if (!activityId) return
    
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo || !userInfo.openId) {
      this.setData({
        hasVotedForCandidate: false,
        voteStatus: {
          totalVoted: 0,
          voteLimit: 1,
          remainingVotes: 1,
          canVoteMore: true,
          votedCandidateIds: []
        }
      })
      return
    }
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'voteManager',
        data: {
          action: 'getVoteStatus',
          activityId: activityId,
          candidateId: candidate.id // 传入当前候选人ID
        }
      })
      
      const response = result.result as any
      if (response && response.success) {
        console.log('投票状态检查结果:', response.data)
        this.setData({
          hasVotedForCandidate: response.data.hasVotedForCandidate,
          voteStatus: {
            totalVoted: response.data.totalVoted,
            voteLimit: response.data.voteLimit,
            remainingVotes: response.data.remainingVotes,
            canVoteMore: response.data.canVoteMore,
            votedCandidateIds: response.data.votedCandidateIds || []
          }
        })
      }
    } catch (error) {
      console.error('检查投票状态失败:', error)
    }
  },

  // 获取选手详情
  async getCandidateDetail(id: string) {
    try {
      wx.showLoading({
        title: '加载中...'
      })
      
      const result = await wx.cloud.callFunction({
        name: 'candidateManager',
        data: {
          action: 'getDetail',
          candidateId: id
        }
      })
      
      const response = result.result as any
      if (response && response.success) {
        const candidate = response.data
        
        // 确保activityId正确设置
        let currentActivityId = this.data.activityId
        if (!currentActivityId && candidate.activityId) {
          console.log('使用候选人的activityId:', candidate.activityId)
          currentActivityId = candidate.activityId
          this.setData({
            activityId: candidate.activityId
          })
        }
        
        console.log('最终使用的activityId:', currentActivityId)
        
        // 计算排名
        const rank = await this.calculateRank(candidate.votes, currentActivityId || candidate.activityId)
        
        this.setData({
          candidate: {
            ...candidate,
            id: candidate._id,
            rank: rank
          },
          loading: false
        })
        
        // 重新检查投票状态（现在有了正确的activityId）
        if (currentActivityId) {
          this.checkVoteStatus()
        }
      } else {
        wx.showToast({
          title: (response && response.message) || '获取数据失败',
          icon: 'error'
        })
        this.setData({ loading: false })
      }
    } catch (error) {
      console.error('获取选手详情失败:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'error'
      })
      this.setData({ loading: false })
    } finally {
      wx.hideLoading()
    }
  },

  // 计算排名
  async calculateRank(votes: number, activityId: string) {
    try {
      const result = await wx.cloud.callFunction({
        name: 'candidateManager',
        data: {
          action: 'getList',
          activityId: activityId
        }
      })
      
      const response = result.result as any
      if (response && response.success) {
        // 修复：获取正确的候选人数组，并添加验证
        const candidatesData = response.data
        let candidates = []
        
        // 检查数据结构
        if (candidatesData && candidatesData.list && Array.isArray(candidatesData.list)) {
          candidates = candidatesData.list
        } else if (Array.isArray(candidatesData)) {
          candidates = candidatesData
        } else {
          console.error('候选人数据格式错误:', candidatesData)
          return 1
        }
        
        // 确保candidates是数组且不为空
        if (!Array.isArray(candidates) || candidates.length === 0) {
          console.warn('候选人数据为空或不是数组:', candidates)
          return 1
        }
        
        const sortedCandidates = candidates.sort((a: any, b: any) => b.votes - a.votes)
        const rank = sortedCandidates.findIndex((c: any) => c.votes <= votes) + 1
        return rank || candidates.length
      }
    } catch (error) {
      console.error('计算排名失败:', error)
    }
    return 1
  },

  // 返回上一页
  goBack() {
    // 手动返回前先停止音频
    console.log('手动返回，停止所有媒体播放')
    this.stopAllMedia()
    wx.navigateBack()
  },

  // 为选手投票
  async voteForCandidate() {
    const { candidate, activityId, hasVotedForCandidate, voteStatus } = this.data
    
    console.log('=== 投票调试信息 ===')
    console.log('候选人信息:', candidate)
    console.log('活动ID:', activityId)
    console.log('已为此候选人投票:', hasVotedForCandidate)
    console.log('投票状态:', voteStatus)
    
    // 检查用户是否已登录
    const userInfo = wx.getStorageSync('userInfo')
    console.log('用户信息:', userInfo)
    
    if (!userInfo || !userInfo.openId) {
      wx.showModal({
        title: '请先登录',
        content: '投票需要先登录，是否前往登录？',
        success: (res) => {
          if (res.confirm) {
            // 跳转前停止音频播放
            this.stopAllMedia()
            wx.switchTab({
              url: '/pages/my/index'
            })
          }
        }
      })
      return
    }

    // 检查是否已为此候选人投票
    if (hasVotedForCandidate) {
      wx.showModal({
        title: '已投票',
        content: '您已经为该候选人投过票了',
        showCancel: false
      })
      return
    }

    // 检查是否还有剩余投票数
    if (!voteStatus.canVoteMore || voteStatus.remainingVotes <= 0) {
      wx.showModal({
        title: '投票已达上限',
        content: `您已投票${voteStatus.totalVoted}次，已达到投票上限`,
        showCancel: false
      })
      return
    }

    // 检查必要参数
    if (!activityId) {
      console.error('活动ID为空')
      wx.showToast({
        title: '活动ID不存在',
        icon: 'none'
      })
      return
    }

    if (!candidate || !candidate.id) {
      console.error('候选人ID为空')
      wx.showToast({
        title: '候选人信息不完整',
        icon: 'none'
      })
      return
    }

    // 确认投票
    wx.showModal({
      title: '投票确认',
      content: `您确定要为"${candidate.name}"投票吗？您还可以投票${voteStatus.remainingVotes}次。`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({
              title: '投票中...'
            })
            
            // 准备投票数据
            const voteData = {
              action: 'vote',
              activityId: activityId,
              candidateIds: [candidate.id]
            }
            
            console.log('投票请求数据:', voteData)
            
            // 使用正确的voteManager云函数进行投票
            const result = await wx.cloud.callFunction({
              name: 'voteManager',
              data: voteData
            })
            
            console.log('云函数返回结果:', result)
            
            wx.hideLoading()
            
            const response = result.result as any
            console.log('云函数响应:', response)
            
            if (response && response.success) {
              const remainingVotes = response.data.remainingVotes || 0
              
              wx.showToast({
                title: remainingVotes > 0 ? `投票成功！还可投票${remainingVotes}次` : '投票成功！',
                icon: 'success',
                duration: 2000
              })
              
              // 更新投票状态
              this.setData({
                hasVotedForCandidate: true,
                'voteStatus.totalVoted': response.data.totalVoted || voteStatus.totalVoted + 1,
                'voteStatus.remainingVotes': remainingVotes,
                'voteStatus.canVoteMore': remainingVotes > 0
              })
              
              // 刷新选手数据
              this.getCandidateDetail(candidate.id)
              
              // 重新检查投票状态
              this.checkVoteStatus()
            } else {
              console.error('投票失败，响应:', response)
              wx.showToast({
                title: response?.message || '投票失败',
                icon: 'none',
                duration: 3000
              })
            }
          } catch (error) {
            console.error('投票失败，错误详情:', error)
            wx.hideLoading()
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  // 视频播放事件
  onVideoPlay() {
    console.log('视频开始播放')
  },

  // 视频暂停事件
  onVideoPause() {
    console.log('视频暂停播放')
  },

  // 视频播放完成事件
  onVideoEnded() {
    console.log('视频播放完成')
  },

  // 视频播放错误事件
  onVideoError(e: any) {
    console.error('视频播放错误:', e.detail)
    const { candidate } = this.data
    
    // 详细的错误信息记录
    console.log('当前视频URL:', candidate.videoUrl)
    console.log('视频错误详情:', JSON.stringify(e.detail))
    
    // 检查视频URL格式
    if (candidate.videoUrl) {
      if (candidate.videoUrl.startsWith('cloud://')) {
        console.log('检测到云存储文件ID格式')
        // 尝试获取临时链接
        this.getTempVideoUrl(candidate.videoUrl)
      } else if (candidate.videoUrl.startsWith('http')) {
        console.log('检测到HTTP URL格式')
      } else if (candidate.videoUrl.startsWith('wxfile://')) {
        console.log('检测到本地临时文件格式')
      } else {
        console.log('未知的视频URL格式')
      }
    } else {
      console.log('视频URL为空')
    }
    
    wx.showModal({
      title: '视频加载失败',
      content: '视频文件可能已损坏或不存在，请联系管理员处理',
      showCancel: true,
      cancelText: '忽略',
      confirmText: '重试',
      success: (res) => {
        if (res.confirm) {
          // 重新获取候选人数据
          this.getCandidateDetail(candidate.id)
        }
      }
    })
  },
  
  // 获取云存储文件的临时链接
  async getTempVideoUrl(fileID: string) {
    try {
      console.log('尝试获取云存储文件临时链接:', fileID)
      const result = await wx.cloud.getTempFileURL({
        fileList: [fileID]
      })
      
      console.log('临时链接获取结果:', result)
      
      if (result.fileList && result.fileList.length > 0) {
        const fileInfo = result.fileList[0]
        if (fileInfo.status === 0) {
          console.log('临时链接获取成功:', fileInfo.tempFileURL)
          // 更新视频URL为临时链接
          this.setData({
            'candidate.videoUrl': fileInfo.tempFileURL
          })
        } else {
          console.error('获取临时链接失败:', fileInfo.errMsg)
        }
      }
    } catch (error) {
      console.error('获取临时链接出错:', error)
    }
  },

  // 预览图片
  previewImage(e: any) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.candidate.images[index],
      urls: this.data.candidate.images
    })
  },

  // 切换描述展开状态
  toggleDescription() {
    this.setData({
      isDescExpanded: !this.data.isDescExpanded
    })
  },

  // 切换音频播放状态
  toggleAudio() {
    const { audioPlaying, audioContext, candidate } = this.data
    
    if (!candidate.audioUrl) {
      wx.showToast({
        title: '音频文件不存在',
        icon: 'none'
      })
      return
    }

    if (audioContext) {
      // 如果已有音频上下文，直接播放或暂停
      if (audioPlaying) {
        audioContext.pause()
      } else {
        audioContext.play()
      }
    } else {
      // 如果没有音频上下文，创建新的
      this.playAudio()
    }
  },

  // 播放音频
  async playAudio() {
    const { candidate, audioContext: existingAudioContext } = this.data
    
    // 如果已存在音频上下文且源相同，直接播放
    if (existingAudioContext && existingAudioContext.src) {
      existingAudioContext.play()
      return
    }
    
    // 如果有旧的音频上下文，先销毁它
    if (existingAudioContext) {
      existingAudioContext.destroy()
    }
    
    try {
      // 创建新的音频上下文
      const audioContext = wx.createInnerAudioContext()
      
      // 设置音频源
      if (candidate.audioUrl.startsWith('cloud://')) {
        // 如果是云存储文件，需要获取临时链接
        const result = await wx.cloud.getTempFileURL({
          fileList: [candidate.audioUrl]
        })
        
        if (result.fileList && result.fileList.length > 0 && result.fileList[0].status === 0) {
          audioContext.src = result.fileList[0].tempFileURL
        } else {
          throw new Error('获取音频临时链接失败')
        }
      } else {
        audioContext.src = candidate.audioUrl
      }

      // 设置音频事件监听
      audioContext.onPlay(() => {
        console.log('音频开始播放')
        this.setData({
          audioPlaying: true
        })
      })

      audioContext.onPause(() => {
        console.log('音频暂停')
        this.setData({
          audioPlaying: false
        })
      })

      audioContext.onEnded(() => {
        console.log('音频播放完成')
        this.setData({
          audioPlaying: false,
          audioCurrentTime: 0,
          audioCurrentTimeFormatted: '00:00',
          audioProgress: 0
        })
      })

      audioContext.onError((err) => {
        console.error('音频播放错误:', err)
        
        // 确保在错误时也停止音频并清理资源
        try {
          if (audioContext) {
            audioContext.stop()
            audioContext.destroy()
          }
        } catch (e) {
          console.error('清理错误音频上下文时出错:', e)
        }
        
        wx.showToast({
          title: '音频播放失败',
          icon: 'none'
        })
        
        // 重置所有音频相关状态
        this.setData({
          audioContext: null,
          audioPlaying: false,
          audioCurrentTime: 0,
          audioCurrentTimeFormatted: '00:00',
          audioProgress: 0,
          audioDuration: 0,
          audioDurationFormatted: '00:00'
        })
      })

      // 监听音频加载完成，获取总时长
      audioContext.onCanplay(() => {
        console.log('音频可以播放，时长:', audioContext.duration)
        const duration = audioContext.duration || 0
        this.setData({
          audioDuration: duration,
          audioDurationFormatted: this.formatTime(duration)
        })
      })

      // 监听播放进度
      audioContext.onTimeUpdate(() => {
        const currentTime = audioContext.currentTime
        const duration = audioContext.duration || this.data.audioDuration
        const progress = duration > 0 ? (currentTime / duration) * 100 : 0
        
        this.setData({
          audioCurrentTime: currentTime,
          audioCurrentTimeFormatted: this.formatTime(currentTime),
          audioProgress: progress
        })
      })

      // 保存音频上下文并开始播放
      this.setData({
        audioContext: audioContext
      })
      
      audioContext.play()
      
    } catch (error) {
      console.error('创建音频播放失败:', error)
      wx.showToast({
        title: '音频播放失败',
        icon: 'none'
      })
    }
  },

  // 拖拽进度条
  onAudioProgressChange(e: any) {
    const { audioContext, audioDuration } = this.data
    if (!audioContext || audioDuration <= 0) return
    
    const progress = e.detail.value
    const seekTime = (progress / 100) * audioDuration
    
    audioContext.seek(seekTime)
    this.setData({
      audioProgress: progress,
      audioCurrentTime: seekTime,
      audioCurrentTimeFormatted: this.formatTime(seekTime)
    })
  },

  // 实时拖动反馈
  onAudioProgressInput(e: any) {
    const { audioDuration } = this.data
    if (audioDuration <= 0) return
    
    const progress = e.detail.value
    const seekTime = (progress / 100) * audioDuration
    
    this.setData({
      audioProgress: progress,
      audioCurrentTime: seekTime,
      audioCurrentTimeFormatted: this.formatTime(seekTime)
    })
  },

  // 格式化时间显示
  formatTime(seconds: number): string {
    if (isNaN(seconds) || seconds < 0) return '00:00'
    
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  },

  // 停止所有媒体播放
  stopAllMedia() {
    const { audioContext } = this.data
    
    console.log('stopAllMedia被调用，当前音频上下文:', audioContext)
    
    // 停止音频
    if (audioContext) {
      try {
        // 先停止播放
        audioContext.stop()
        console.log('音频已停止播放')
        
        // 移除所有事件监听
        audioContext.offPlay()
        audioContext.offPause()
        audioContext.offEnded()
        audioContext.offError()
        audioContext.offCanplay()
        audioContext.offTimeUpdate()
        console.log('音频事件监听已移除')
        
        // 销毁音频上下文
        audioContext.destroy()
        console.log('音频上下文已销毁')
        
        // 重置音频相关状态
        this.setData({
          audioContext: null,
          audioPlaying: false,
          audioCurrentTime: 0,
          audioCurrentTimeFormatted: '00:00',
          audioProgress: 0,
          audioDuration: 0,
          audioDurationFormatted: '00:00'
        })
        console.log('音频状态已重置')
      } catch (error) {
        console.error('停止音频时出错:', error)
      }
    } else {
      console.log('没有活跃的音频上下文')
    }
    
    // 停止视频 - 获取页面中的video组件
    try {
      const videoContext = wx.createVideoContext('candidateVideo', this)
      if (videoContext) {
        videoContext.pause()
        console.log('视频已暂停')
      }
    } catch (error) {
      console.error('停止视频时出错:', error)
    }
  },

  // 分享
  onShareAppMessage() {
    const { candidate } = this.data
    return {
      title: `为${candidate.name}投票`,
      path: `/pages/candidate/detail/index?id=${candidate.id}&activityId=${this.data.activityId}`,
      imageUrl: candidate.images.length > 0 ? candidate.images[0] : ''
    }
  }
}) 